<?php

namespace app\api;

use app\BaseController;
use app\api\model\OpusNumberModel;
use think\cache\driver\Redis;
use think\Request;
use app\api\common;
use Request\Request as RequestServerModel;
use app\admin\model\log\Log as LogModel;
use SnowFlake\Snowflake;
use think\facade\Session;
use think\facade\Cache;
use think\App;
use app\common as appCommon;
use app\api\controller\Common as authCommon;
/**
 * @title server 基类
 *
 */
class ServerBase extends authCommon
{
    public $writer_field = ['writer_name','writer_head_img','fans_num'];
    public $SUCCESS = "成功";
    public $ERROR = "失败";
    public $PINDEX = 10;
    public $PAGE = 1;
    public static $s_primary_key_model;
	public $_before_data_start;
	public function sendMessage($_mobile,$_data,$_field){
    	$_app_common=new appCommon();
    	if($_app_common->replaceMessage($_mobile,$_data,$_field)==false){
    		$this->ERROR=$_app_common->ERROR;
    		$this->CODE=$_app_common->CODE;
    		return false;
    	}
    	return true;
    }
    public function getOssImage($_file){
    	$_files=$_file."?x-oss-process=image/resize,m_fill,h_400,w_320,quality,q_100";
    	return $_files;
    }
    //除了统一返回函数外另一个返回入口
    public function checkAuth(){
		$_auth_common=new \app\api\controller\Common($this->app);
		if(!$_auth_common->_no_login){
			global $user;
			if(!$user){
				echo json_encode(['code'=>1000,'msg'=>'未获取到用户数据']);exit;
			}
			$this->auth=$user;
    	}
    }
    public function getUserId(){
    	return $this->auth['id']?$this->auth['id']:0;
    }
    
    public function beforeLog($operation_function, $model, $function, $where, $field, $name)
    {
        //1.查询
        $_common = new common();
        if (is_array($function)) {
            foreach ($function as $k => $v) {
            	
                if (!empty($where[$v])) {
                    $_before_data = $model->$v($where[$v], $field);
                } else {
                    $_before_data = $model->$v($where, $field);
                }
                if($k==0){
            		$this->_before_data_start=$_before_data;
            	}
                $_common->requestLog($operation_function, 'update', $_before_data, $name . "之前");
            }
        } else {
            $_before_data = $model->$function($where, $field);
            $_common->requestLog($operation_function, 'update', $_before_data, $name . "之前");
        }
        return $_before_data;
    }
    
    /**
     * @purpose 处理搜索 时的json数据
     */
 	public function checkParam(){
    	$_param=$this->REQUEST->param();
    	$_data=[];
    	foreach($_param as $k=>$v){
    		
    		if( $k == 'searchParams' )
    		{
    			$searchParams=json_decode($v,true);
    			if(!empty($searchParams ))
    			{
    				foreach($searchParams as $ka => $kv )
    				{
    					$_data[$ka]=$kv;
    				}	
    			}
    			continue;
    		}
    		$_data[$k]=$v;
    	}
    	return $_data;
    }
    
    public function afterLog($operation_function, $model, $function, $where, $field, $name)
    {
        //1.查询
        $_common = new common();
        if (is_array($function)) {
            foreach ($function as $k => $v) {
                if (!empty($where[$v])) {
                    $_after_data = $model->$v($where[$v], $field);
                } else {
                    $_after_data = $model->$v($where, $field);
                }
                $_common->requestLog($operation_function, 'update', $_after_data, $name . "之后");
            }
        } else {
            $_after_data = $model->$function($where, $field);
            $_common->requestLog($operation_function, 'update', $_after_data, $name . "之后");
        }
        return $_after_data;
    }
    /**
     * 获取分页的数量
     *
     */
    public function getPageCount($_count)
    {
        $_pindex = $this->PINDEX;
       // $_count = ceil($_count / $_pindex);
        return $_count;
    }

    /**
     * 获取分页limit
     */
    public function getPage($data)
    {
        $data[]=$data['page']??1;
        $data[]=$data['limit']??15;
        return $data;
    }

    //记录所有CODE和msg
    public function getMessageCode($field, $flag)
    {
        if ($flag == 1) {
            $this->ERROR = config($field . '.msg');
        }
        $this->CODE = config($field . '.code');
        $this->SUCCESS = config($field . '.msg');
    }
    //自定义的返回msg和code
    public function setOtherMessageCode($msg, $flag,$code)
    {
        if ($flag == 1) {
            $this->ERROR = $msg;
        }
        $this->CODE =$code;
        $this->SUCCESS = $msg;
    }
    
    
    public function return_server($_data,$message_field){
    	if(!$_data){
			$this->getMessageCode('adminMessage.error.'.$message_field,1);
			return false;
		}
		$this->getMessageCode('adminMessage.success.'.$message_field,2);
		return true;
    }
    
    function getLimit(){
        if(check_request($this->request,"limit")){
            return $this->request['limit'];
        }else{
            return 15;
        }
    }

    //设置锁定作品编码
    function setRedisLockOrderOpusOpusNumber($opus_number_id=[]){
        $redis=new Redis();
        $redis->set2('lockOrderOpusOpusNumber'.$opus_number_id,1,900);
    }
    //重复点击
    function checkRepeatClick($key){
        $redis=new redis();
        if($redis->get($key)){
            show_json('code_common.error','请勿重复点击',true);
        }
        $redis->set($key,1,2);
    }
    
    public function checkDataId($_data=array(),$_field=array(),$_flag=1){
    	if($_flag==1){
    		foreach($_field as $k=>$v){
    			$_data[$v]=(string) $_data[$v];
    		}
    	}else{
    		foreach($_field as $k=>$v)
    		{
    			foreach($_data as $ka=>$kv)
    			{
    				$_data[$ka][$v]=(string) $kv[$v];
    				continue;
    			}
    		}
    	}
    	return $_data;
    }
    
    /**
	 * @title redis 检测是否是重复提交
	 */
	public function checkRedis(){
		$_user=$this->auth;
		$_param=$this->REQUEST->param();
		$_redis_key=md5('createGoodsOrder_'.$_user['id'].json_encode($_param));
    	$redis=new Redis();
    	$this->redis=$redis;
    	$this->redis_key=$_redis_key;
  		$_sleep_time=10; //设置过期时间10秒
  		$_time=time()+$_sleep_time;//设置意外情况下的解锁时间
  		$_result=$redis->setNx($_redis_key,$_time);//处理并发情况下设置锁
      	if(!$_result){
      		if($redis->get($_redis_key)<time()){
				$redis->del($_redis_key);//删除以前死锁
			}
      		$this->getMessageCode('adminMessage.cache',1);
      		return false;
      	}
      	//设置过期时间
      	if($redis->ttl($_redis_key)==-1){
			$redis->expire($_redis_key,$_sleep_time);
		}
      	return $_redis_key;
	}
}

?>